package com.lovo.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lovo.bean.UserInfoBean;
import com.lovo.dao.IUserInfoDAO;
import com.lovo.service.IUserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lovo.util.RedisUtil;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bdk
 * @since 2021-03-02
 */
@Service
@Transactional(rollbackFor = Throwable.class)
public class UserInfoServiceImpl extends ServiceImpl<IUserInfoDAO, UserInfoBean> implements IUserInfoService {
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private IUserInfoDAO userInfoDAO;
    @Override
    public Object selectAll(Integer page,Integer size) {
        long start = System.currentTimeMillis();
        // 从缓存中获取数据
//        Object obj = redisUtil.get("selectAllUser_"+page+"_"+size);
        // 从redis中的hashmap获取数据
        Object obj = redisUtil.hget("user",page+"_"+size);
        if(obj == null){
            // 如果缓存中没有数据，从数据库获取，并加入到缓存
            IPage pageObject = new Page(page,size);
            obj = userInfoDAO.selectPage(pageObject,null);
//            redisUtil.set("selectAllUser_"+page+"_"+size,obj,60 * 60);
            redisUtil.hset("user",page+"_"+size,obj,60 * 60);
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);
        return obj;
    }

    public void add(UserInfoBean userInfoBean){
//        Long id = redisUtil.incr("userId",1);
//        userInfoBean.setUserId(id);
//        userInfoDAO.insert(userInfoBean);
        redisUtil.del("user");
        userInfoDAO.insert(userInfoBean);
    }

    @Override
    public UserInfoBean selectByUserName(String userName) {
        return userInfoDAO.selectByUserName(userName);
    }

    @Override
    public void delete(Long userId) {
        redisUtil.del("user");
        userInfoDAO.deleteFromUserRoleByUserId(userId);
        userInfoDAO.deleteById(userId);
    }

    @Override
    public void addUserRole(Long userId, List<Long> roleIds) {
        userInfoDAO.deleteFromUserRoleByUserId(userId);
        for(Long roleId:roleIds){
            userInfoDAO.insertUserRole(userId,roleId);
        }
    }


}
